import { DateFormats } from "./type";

export function format(date: Date, fmt = 'yyyy/MM/dd') {
  var o: DateFormats = {
    "M+": date.getMonth() + 1, //月份
    "d+": date.getDate(), //日
    "h+": date.getHours(), //小时
    "m+": date.getMinutes(), //分
    "s+": date.getSeconds(), //秒
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度
    "S": date.getMilliseconds() //毫秒
  }
  let result = fmt.replace(/(y+)/g, (match, p1) => {
    return (date.getFullYear() + "").slice(-p1.length);
  });

  for (let k in o) {
    result = result.replace(new RegExp("(" + k + ")", "g"), (match) => {
      let value = o[k];
      if (match.length > 1) {
        value = ("0" + value).slice(-match.length); // 确保值至少有 match.length 位
      }
      return value;
    });
  }

  return result;
}